﻿<!-- 统计分析页面 -->

<template>
  <div class="statistics">
    <h1 class="page-title">数据统计</h1>
    
    <div class="statistics-tabs">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="系统使用情况" name="system">
          <student-analysis />
        </el-tab-pane>
        
        <el-tab-pane label="学生学习情况" name="student">
          <div class="tab-content">
            <div class="filter-bar">
              <el-select v-model="selectedClass" placeholder="选择班级" @change="fetchStudentLearningMetrics">
                <el-option
                  v-for="item in classesList"
                  :key="item.id"
                  :label="item.className"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-select v-model="selectedPeriod" placeholder="时间周期" @change="fetchStudentLearningMetrics">
                <el-option label="本周" value="week"></el-option>
                <el-option label="本月" value="month"></el-option>
                <el-option label="本学期" value="semester"></el-option>
                <el-option label="全年" value="year"></el-option>
              </el-select>
            </div>
            
            <div class="chart-row">
              <div class="chart-card">
                <h3 class="chart-title">正确率趋势</h3>
                <div class="chart-container" ref="correctRateTrendChart"></div>
              </div>
              <div class="chart-card">
                <h3 class="chart-title">知识点掌握情况</h3>
                <div class="chart-container" ref="knowledgeMasteryChart"></div>
              </div>
            </div>
            <div class="chart-row">
              <div class="chart-card">
                <h3 class="chart-title">高频错误点统计</h3>
                <div class="chart-container" ref="errorPointsChart"></div>
              </div>
            </div>
            <div class="student-ranking-section">
              <h3 class="section-title">学生学习排名</h3>
              <el-table :data="studentRanking" style="width: 100%" stripe>
                <el-table-column prop="name" label="学生姓名" width="120"></el-table-column>
                <el-table-column prop="className" label="班级" width="120"></el-table-column>
                <el-table-column prop="sessionCount" label="练习次数" width="100"></el-table-column>
                <el-table-column prop="totalExercises" label="习题数量" width="100"></el-table-column>
                <el-table-column prop="correctExercises" label="正确数量" width="100"></el-table-column>
                <el-table-column prop="accuracy" label="平均正确率">
                  <template #default="scope">
                    <div class="progress-bar-wrapper">
                      <el-progress :percentage="parseFloat(scope.row.accuracy)" :format="percentFormatter"></el-progress>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <div class="subject-comparison-section">
              <h3 class="section-title">学科学习效果比较</h3>
              <el-table :data="subjectStats.slice(0, 1)" style="width: 100%" stripe>
                <el-table-column prop="subject" label="科目统计" width="120"></el-table-column>
                <el-table-column prop="studentCount" label="学生人数" width="100"></el-table-column>
                <el-table-column prop="sessionCount" label="总练习次数" width="120"></el-table-column>
                <el-table-column prop="exerciseCount" label="总习题数量" width="120"></el-table-column>
                <el-table-column prop="accuracy" label="平均正确率">
                  <template #default="scope">
                    <div class="progress-bar-wrapper">
                      <el-progress :percentage="scope.row.accuracy" :format="percentFormatter"></el-progress>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="教师教学情况" name="teacher">
          <div class="tab-content">
            <!-- 筛选条件 -->
            <div class="filter-bar">
              <el-select v-model="selectedDepartment" placeholder="选择教研组" @change="handleDepartmentChange">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-select v-model="teacherDateRange" placeholder="时间周期" @change="handleDateRangeChange">
                <el-option label="本周" value="week"></el-option>
                <el-option label="本月" value="month"></el-option>
                <el-option label="本学期" value="semester"></el-option>
                <el-option label="全年" value="year"></el-option>
              </el-select>
            </div>
            
            <!-- 教学效率指数部分 -->
            <div class="efficiency-section">
              <h2 class="section-title">教学效率指数分析</h2>
              
              <div class="chart-row">
                <div class="chart-card">
                  <h3 class="chart-title">备课与修正耗时</h3>
                  <div class="chart-container" ref="lessonPrepTimeChart"></div>
                </div>
                <div class="chart-card">
                  <h3 class="chart-title">课后练习设计与修正耗时</h3>
                  <div class="chart-container" ref="exercisePrepTimeChart"></div>
                </div>
              </div>
              
              <div class="chart-row">
                <div class="chart-card">
                  <h3 class="chart-title">课程优化方向</h3>
                  <div class="chart-container" ref="courseOptimizationChart"></div>
                </div>
                <div class="chart-card">
                  <h3 class="chart-title">教学效率趋势</h3>
                  <div class="chart-container" ref="efficiencyTrendChart"></div>
                </div>
              </div>
              
              <div class="teacher-efficiency-table">
                <h2 class="section-title">教师效率详情</h2>
                <el-table :data="teacherEfficiencyData" style="width: 100%" stripe>
                  <el-table-column prop="teacherName" label="教师姓名" width="100"></el-table-column>
                  <el-table-column label="教研组" width="120">
                    <template #default="scope">
                      <span>{{ getDepartmentBySubject(scope.row) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="备课时间(分钟)" width="120">
                    <template #default="scope">
                      <div class="time-indicator">
                        <span :class="getPrepTimeClass(scope.row.prepTime)">{{ scope.row.prepTime }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="练习设计(分钟)" width="120">
                    <template #default="scope">
                      <div class="time-indicator">
                        <span :class="getExerciseTimeClass(scope.row.exerciseTime)">{{ scope.row.exerciseTime }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="efficiency" label="效率指数" width="150">
                    <template #default="scope">
                      <div class="progress-bar-wrapper">
                        <el-progress :percentage="scope.row.efficiency" :format="percentFormatter" :status="getEfficiencyStatus(scope.row.efficiency)"></el-progress>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="optimizationFocus" label="优化建议" min-width="150"></el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
// 导入所需的库和组件
import { ref, reactive, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import StudentAnalysis from './statistics/StudentAnalysis.vue';

export default {
  name: 'Statistics',
  components: {
    StudentAnalysis
  },
  setup() {
    // 激活的标签页
    const activeTab = ref('system');

    // 学生学习情况相关图表引用
    const correctRateTrendChart = ref(null);
    const knowledgeMasteryChart = ref(null);
    const errorPointsChart = ref(null);
    
    // 教师相关图表引用
    const lessonPrepTimeChart = ref(null);
    const exercisePrepTimeChart = ref(null);
    const courseOptimizationChart = ref(null);
    const efficiencyTrendChart = ref(null);
    
    // 图表实例集合
    const charts = reactive({});
  
    // 过滤条件
    const selectedClass = ref('');
    const selectedPeriod = ref('month');  // 默认选择本月数据
    
    // 新增教师过滤条件
    const selectedDepartment = ref('all'); // 默认选择全部教研组
    const teacherDateRange = ref('month'); // 默认选择本月数据
    
    // 学生学习数据
    const learningMetricsData = ref(null);
    const studentRanking = ref([]);
    const subjectStats = ref([]);
    
    // 教师效率数据
    const teacherEfficiencyData = ref([]);
    
    // 格式化百分比
    const percentFormatter = (percentage) => {
      return percentage.toFixed(1) + '%';
    };

    // 班级列表数据
    const classesList = ref([]);
    
    // 教研组列表数据
    const departmentList = ref([
      { id: 'all', name: '全部' },
      { id: 'chinese', name: '语文教研组' },
      { id: 'math', name: '数学教研组' },
      { id: 'english', name: '英语教研组' },
      { id: 'physics', name: '物理教研组' },
      { id: 'chemistry', name: '化学教研组' }
    ]);
    
    // 初始化所有图表
    const initCharts = () => {
      // 在系统使用情况标签页中不再需要初始化这些图表
      // 因为已经由StudentAnalysis组件接管
      
      // 确保学生和教师标签页的图表仍然正常工作
      if (activeTab.value === 'student' && selectedClass.value) {
        fetchStudentLearningMetrics();
      }
      
      if (activeTab.value === 'teacher') {
        fetchTeacherStatistics();
      }
};

    // 获取班级列表
    const fetchClassesList = async () => {
      try {
        const response = await axios.get('/api/admin/classes');
        classesList.value = response.data.data || [];
        
        if (classesList.value.length > 0 && !selectedClass.value) {
          selectedClass.value = classesList.value[0].id;
          fetchStudentLearningMetrics();
        }
      } catch (error) {
        console.error('获取班级列表失败:', error);
        ElMessage.error('获取班级列表失败');
      }
};

// 获取学生学习情况数据
const fetchStudentLearningMetrics = async () => {
  if (!selectedClass.value) {
    ElMessage.warning('请选择班级');
    return;
  }
  
  try {
    // 构建请求参数
    const params = {};
    params.classId = selectedClass.value;
    params.period = selectedPeriod.value;
    
    // 调用学生学习情况统计API
    const response = await axios.get('/api/admin/statistics/student-learning', { params });
    
    if (response.data.success) {
      learningMetricsData.value = response.data.data;
      
      // 调用学习进度统计API获取排名和学科比较数据
      const progressResponse = await axios.get('/api/admin/statistics/learning-progress', { params });
      
      if (progressResponse.data.success) {
        // 处理学生排名数据
        studentRanking.value = progressResponse.data.data.studentRanking || [];
        // 处理学科统计数据
        subjectStats.value = progressResponse.data.data.subjectStats || [];
      }
      
      // 初始化图表
      nextTick(() => {
        initCorrectRateTrendChart();
        initKnowledgeMasteryChart();
        initErrorPointsChart();
      });
    } else {
      ElMessage.error(response.data.message || '获取学生学习统计数据失败');
    }
  } catch (error) {
    console.error('获取学生学习统计数据失败:', error);
    ElMessage.error('获取学生学习统计数据失败');
  }
};

// 初始化正确率趋势图表
const initCorrectRateTrendChart = () => {
  if (!correctRateTrendChart.value) return;
  
  const chart = echarts.init(correctRateTrendChart.value);
  charts.correctRateTrend = chart;
  
  // 从API返回数据中提取正确率趋势数据
  const trend = learningMetricsData.value?.correctRateTrend || [];
  const dates = trend.map(item => item.date);
  const rates = trend.map(item => item.rate);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: '{b}<br/>{a}: {c}%'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '正确率',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      name: '正确率',
      data: rates,
      type: 'line',
      smooth: true,
      lineStyle: {
        width: 3,
        color: '#5470C6'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(84,112,198,0.5)'
          }, {
            offset: 1,
            color: 'rgba(84,112,198,0.1)'
          }]
        }
      }
    }]
  };
  
  chart.setOption(option);
};

// 初始化知识点掌握情况图表
const initKnowledgeMasteryChart = () => {
  if (!knowledgeMasteryChart.value) return;
  
  const chart = echarts.init(knowledgeMasteryChart.value);
  charts.knowledgeMastery = chart;
  
  // 从API返回数据中提取知识点掌握情况数据
  const mastery = learningMetricsData.value?.knowledgeMastery || [];
  const points = mastery.map(item => item.point);
  const levels = mastery.map(item => parseFloat(item.level).toFixed(1));
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>{a}: {c}%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    yAxis: {
      type: 'category',
      data: points,
      nameGap: 25
    },
    series: [{
      name: '掌握程度',
      type: 'bar',
      data: levels,
      itemStyle: {
        color: function(params) {
          // 根据掌握程度设置不同颜色
          const level = parseFloat(params.value);
          if (level >= 80) return '#67C23A';  // 优秀
          if (level >= 60) return '#E6A23C';  // 良好
          return '#F56C6C';  // 需要加强
        }
      },
      label: {
        show: true,
        position: 'right',
        formatter: '{c}%'
      }
    }]
  };
  
  chart.setOption(option);
};

// 初始化高频错误点图表
const initErrorPointsChart = () => {
  if (!errorPointsChart.value) return;
  
  const chart = echarts.init(errorPointsChart.value);
  charts.errorPoints = chart;
  
  // 从API返回数据中提取高频错误点数据
  const errorPoints = learningMetricsData.value?.highErrorPoints || [];
  const points = errorPoints.map(item => item.point);
  const frequencies = errorPoints.map(item => item.frequency);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: points
    },
    series: [{
      name: '错误频率',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {c}次'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '16',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: true
      },
      data: errorPoints.map(item => ({
        name: item.point,
        value: item.frequency
      }))
    }]
  };
  
  chart.setOption(option);
};

// 获取教师统计数据
const fetchTeacherStatistics = async () => {
  await nextTick();
  
  try {
    console.log('请求教师效率数据，API路径：/api/admin/statistics/teacher-efficiency-data');
    
    // 调用API获取教师教学效率数据 - 不传递任何参数，因为该接口不支持参数
    const response = await axios.get('/api/admin/statistics/teacher-efficiency-data');
    
    if (response.data.success) {
      console.log('获取教师效率数据成功：', response.data);
      // 更新效率数据并处理缺失字段
      teacherEfficiencyData.value = (response.data.data.efficiencyData || []).map(item => {
        // 如果没有department字段，根据teacherName或subject推断
        if (!item.department) {
          item.subject = item.subject || '';
        }
        return item;
      });
      
      // 更新优化方向数据（用于课程优化方向图表）
      const optimizationData = response.data.data.optimizationData || [];
      
      // 更新趋势数据（用于效率趋势图表）
      const teacherTrends = response.data.data.teacherTrends || {};
      
      // 初始化教学效率相关图表
      initLessonPrepTimeChart();
      initExercisePrepTimeChart();
      initCourseOptimizationChart(optimizationData);
      initEfficiencyTrendChart(teacherTrends);
    } else {
      console.error('获取教师效率数据失败：', response.data);
      ElMessage.error(response.data.message || '获取教师效率数据失败');
    }
  } catch (error) {
    console.error('获取教师效率数据失败:', error);
    ElMessage.error('获取教师效率数据失败');
  }
};

// 根据教师信息推断教研组
const getDepartmentBySubject = (teacher) => {
  // 首先检查是否有department字段
  if (teacher.department) {
    return teacher.department;
  }
  
  // 然后检查是否有subject字段
  if (teacher.subject) {
    const subjectMap = {
      'chinese': '语文教研组',
      'math': '数学教研组',
      'english': '英语教研组',
      'physics': '物理教研组',
      'chemistry': '化学教研组',
      'biology': '生物教研组',
      'history': '历史教研组',
      'geography': '地理教研组',
      'politics': '政治教研组'
    };
    
    return subjectMap[teacher.subject] || `${teacher.subject}教研组`;
  }
  
  // 如果没有可用信息，返回默认值
  return '未知教研组';
};

// 根据效率值获取进度条状态
const getEfficiencyStatus = (efficiency) => {
  if (efficiency >= 85) return 'success';
  if (efficiency >= 70) return 'warning';
  return 'exception';
};

// 根据备课耗时获取样式类
const getPrepTimeClass = (time) => {
  if (time <= 75) return 'time-good';
  if (time <= 85) return 'time-normal';
  return 'time-high';
};

// 根据练习设计耗时获取样式类
const getExerciseTimeClass = (time) => {
  if (time <= 50) return 'time-good';
  if (time <= 60) return 'time-normal';
  return 'time-high';
};

// 初始化备课与修正耗时图表
const initLessonPrepTimeChart = () => {
  if (!lessonPrepTimeChart.value) return;
  
  const chart = echarts.init(lessonPrepTimeChart.value);
  charts.lessonPrepTime = chart;
  
  // 仅使用前5名教师数据，避免图表过于拥挤
  const topTeachers = teacherEfficiencyData.value.slice(0, 5);
  const teacherNames = topTeachers.map(item => item.teacherName);
  const prepTimes = topTeachers.map(item => item.prepTime);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>{a}: {c}分钟'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: teacherNames,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '时间(分钟)'
    },
    series: [{
      name: '备课时间',
      data: prepTimes,
      type: 'bar',
      barWidth: '40%',
      itemStyle: {
        color: function(params) {
          // 根据耗时设置不同颜色
          const value = params.value;
          if (value <= 75) return '#67C23A';  // 绿色 - 效率高
          if (value <= 85) return '#E6A23C';  // 橙色 - 一般
          return '#F56C6C';  // 红色 - 效率低
        }
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}'
      }
    }]
  };
  
  chart.setOption(option);
};

// 初始化课后练习设计与修正耗时图表
const initExercisePrepTimeChart = () => {
  if (!exercisePrepTimeChart.value) return;
  
  const chart = echarts.init(exercisePrepTimeChart.value);
  charts.exercisePrepTime = chart;
  
  // 仅使用前5名教师数据，避免图表过于拥挤
  const topTeachers = teacherEfficiencyData.value.slice(0, 5);
  const teacherNames = topTeachers.map(item => item.teacherName);
  const exerciseTimes = topTeachers.map(item => item.exerciseTime);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>{a}: {c}分钟'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: teacherNames,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '时间(分钟)'
    },
    series: [{
      name: '练习设计时间',
      data: exerciseTimes,
      type: 'bar',
      barWidth: '40%',
      itemStyle: {
        color: function(params) {
          // 根据耗时设置不同颜色
          const value = params.value;
          if (value <= 50) return '#67C23A';  // 绿色 - 效率高
          if (value <= 60) return '#E6A23C';  // 橙色 - 一般
          return '#F56C6C';  // 红色 - 效率低
        }
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}'
      }
    }]
  };
  
  chart.setOption(option);
};

// 初始化课程优化方向图表
const initCourseOptimizationChart = (optimizationData = null) => {
  if (!courseOptimizationChart.value) return;
  
  const chart = echarts.init(courseOptimizationChart.value);
  charts.courseOptimization = chart;
  
  let chartData = [];
  
  if (optimizationData && optimizationData.length > 0) {
    // 使用API返回的优化方向数据
    chartData = optimizationData;
  } else {
    // 统计优化方向出现的次数
    const optimizationCounts = {};
    teacherEfficiencyData.value.forEach(item => {
      if (optimizationCounts[item.optimizationFocus]) {
        optimizationCounts[item.optimizationFocus]++;
      } else {
        optimizationCounts[item.optimizationFocus] = 1;
      }
    });
    
    // 转换为数组格式
    chartData = Object.keys(optimizationCounts).map(key => ({
      name: key,
      value: optimizationCounts[key]
    }));
  }
  
  const option = {
    title: {
      text: '课程优化方向分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.map(item => item.name),
      top: 30
    },
    series: [{
      name: '优化方向',
      type: 'pie',
      radius: '55%',
      center: ['50%', '60%'],
      data: chartData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        formatter: '{b}: {c} ({d}%)'
      }
    }]
  };
  
  chart.setOption(option);
};

// 初始化教学效率趋势图表
const initEfficiencyTrendChart = (teacherTrends = null) => {
  if (!efficiencyTrendChart.value) return;
  
  const chart = echarts.init(efficiencyTrendChart.value);
  charts.efficiencyTrend = chart;
  
  // 默认日期标签
  let dates = ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周'];
  let series = [];
  
  if (teacherTrends && Object.keys(teacherTrends).length > 0) {
    // 使用API返回的趋势数据
    // 限制只显示前5名教师，避免图表过于拥挤
    const topTeachers = Object.keys(teacherTrends).slice(0, 5);
    
    series = topTeachers.map(teacher => ({
      name: teacher,
      type: 'line',
      data: teacherTrends[teacher],
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 2
      }
    }));
  } else {
    // 模拟一些趋势数据
    const efficiencyTrends = {
      '张老师': [75, 78, 80, 83, 85, 88],
      '李老师': [82, 85, 88, 90, 91, 92],
      '王老师': [65, 68, 70, 72, 73, 75],
      '陈老师': [78, 80, 82, 83, 84, 85],
      '刘老师': [70, 72, 74, 75, 76, 78]
    };
    
    series = Object.keys(efficiencyTrends).map(teacher => ({
      name: teacher,
      type: 'line',
      data: efficiencyTrends[teacher],
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 2
      }
    }));
  }
  
  const option = {
    title: {
      text: '教学效率趋势变化',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].name + '<br/>';
        params.forEach(param => {
          result += param.marker + ' ' + param.seriesName + ': ' + param.value + '<br/>';
        });
        return result;
      }
    },
    legend: {
      data: series.map(item => item.name),
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
      top: 80
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '效率指数',
      min: 60,
      max: 100
    },
    series: series
  };
  
  chart.setOption(option);
};

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  Object.values(charts).forEach(chart => {
    chart && chart.resize();
  });
};

// 监听标签页切换
const handleTabChange = async (tab) => {
      if (tab.props.name === 'student' && classesList.value.length === 0) {
    await fetchClassesList();
  }
  
      if (tab.props.name === 'student' && selectedClass.value) {
    fetchStudentLearningMetrics();
  }
  
      if (tab.props.name === 'teacher') {
    fetchTeacherStatistics();
  }
  
  // 调整图表大小
  setTimeout(() => {
    handleResize();
  }, 300);
};

// 教研组变化处理函数
const handleDepartmentChange = () => {
  // 暂时不能根据教研组过滤，因为接口不支持
  ElMessage.info('该接口暂不支持按教研组筛选');
};

// 时间周期变化处理函数
const handleDateRangeChange = () => {
  // 暂时不能根据时间周期过滤，因为接口不支持
  ElMessage.info('该接口暂不支持按时间周期筛选');
};

// 生命周期钩子
onMounted(() => {
  initCharts();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  // 销毁所有图表实例
  Object.values(charts).forEach(chart => {
    chart && chart.dispose();
  });
});
    
    return {
      activeTab,
      handleTabChange,
      // 图表引用
      correctRateTrendChart,
      knowledgeMasteryChart,
      errorPointsChart,
      lessonPrepTimeChart,
      exercisePrepTimeChart,
      courseOptimizationChart,
      efficiencyTrendChart,
      // 过滤条件
      selectedClass,
      selectedPeriod,
      selectedDepartment,
      teacherDateRange,
      // 数据
      classesList,
      departmentList,
      studentRanking,
      subjectStats,
      teacherEfficiencyData,
      // 方法
      fetchClassesList,
      fetchStudentLearningMetrics,
      fetchTeacherStatistics,
      handleDepartmentChange,
      handleDateRangeChange,
      percentFormatter,
      getEfficiencyStatus,
      getPrepTimeClass,
      getExerciseTimeClass,
      getDepartmentBySubject
    };
  }
};
</script>

<style scoped>
.statistics {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #333;
}

.statistics-tabs {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.tab-content {
  margin-top: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.chart-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
}

.chart-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin: 30px 0 15px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.student-ranking-section, 
.subject-comparison-section,
.efficiency-section,
.teacher-efficiency-table {
  margin-top: 30px;
}

.progress-bar-wrapper {
  padding-right: 20px;
}

.time-indicator span {
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: 500;
}

.time-good {
  background-color: #f0f9eb;
  color: #67c23a;
}

.time-normal {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.time-high {
  background-color: #fef0f0;
  color: #f56c6c;
}

.teacher-efficiency-table {
  margin-top: 40px;
}

.efficiency-section {
  margin-top: 10px;
}

@media (max-width: 768px) {
  .chart-row {
    flex-direction: column;
  }
}
</style>
